<?php

namespace app\models;

use app\components\BaseActiveRecord;
use Throwable;
use Yii;
use yii\caching\TagDependency;
use yii\db\ActiveRecord;
use yii\db\Exception;
use yii\db\StaleObjectException;

/**
 * This is the model class for table "{{%user_history}}".
 *
 * @property int $id
 * @property int $uid
 * @property int $book_id
 * @property int $item_id
 * @property string $item_name
 * @property int $item_sort
 * @property string $book_title
 * @property int $create_time
 *
 * @property Book $book
 */
class UserHistory extends BaseActiveRecord {

    const MAX_HISTORY = 60;
    const CACHE_TAG = '%s_history';

    /**
     * {@inheritdoc}
     */
    public static function tableName() {
        return '{{%user_history}}';
    }

    /**
     * {@inheritdoc}
     */
    public function rules() {
        return [
            [['uid', 'book_id', 'item_id', 'item_sort', 'create_time'], 'integer'],
            [['book_title', 'item_name'], 'string', 'max' => 60],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels() {
        return [
            'id' => Yii::t('app', 'ID'),
            'uid' => Yii::t('app', 'Uid'),
            'book_id' => Yii::t('app', 'Book ID'),
            'item_id' => Yii::t('app', 'Item ID'),
            'create_time' => Yii::t('app', 'Create Time'),
        ];
    }

    /**
     * @param $book
     * @param $item
     * @return array
     * @throws StaleObjectException
     * @throws Throwable
     * @throws Exception
     */
    public static function saveHistory($book, $item) {
        $uid = Yii::$app->user->id;
        if (!$uid) {
            return self::retOK();
        }

        $model = self::find()->where("uid = {$uid} and book_id = {$book['id']}")->one();
        if (!$model) {
            $model = new static();
            $model->book_id = $book['id'];
        }

        if (self::find()->where("uid = {$uid}")->count() >= self::MAX_HISTORY) {
            $model = self::find()->where("uid = {$uid}")->orderBy('id asc')->one();
            $model->delete();
        }

        $model->uid = $uid;
        $model->item_id = $item['id'];
        $model->item_sort = $item['sort'];
        $model->item_name = $item['name'];
        $model->create_time = time();
        $model->book_title = $book['title'];
        return $model->save();
    }

    /**
     * @param null $uid
     * @return array|ActiveRecord[]
     */
    public static function getHistory($uid = NULL) {
        if (!$uid) {
            $uid = Yii::$app->user->id;
            if (!$uid) {
                return [];
            }
        }
        $TAG = sprintf(self::CACHE_TAG, $uid);
        $dependency = new TagDependency(['tags' => $TAG]);
        return self::find()->cache(0, $dependency)->where("uid = {$uid}")->orderBy('id desc')->asArray()->all();
    }

    /**
     * @return array
     */
    public static function deleteAllHistory() {
        $uid = Yii::$app->user->id;
        if (!$uid) {
            return self::retOK();
        }
        $where = ['uid' => $uid];
        self::deleteAll($where);
        return self::retOK();
    }

    public function getBook() {
        return $this->hasOne(Book::class, ['id' => 'book_id']);
    }

    public function refreshCache() {
        $TAG = sprintf(self::CACHE_TAG, $this->uid);
        TagDependency::invalidate(Yii::$app->cache, $TAG);
    }
}
